package com.mc.moring.login;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.Gson;
import com.hjq.permissions.Permission;
import com.mc.moring.R;
import com.mc.moring.app.LogUtils;
import com.mc.moring.base.BaseActivity;
import com.mc.moring.base.HttpCallback;
import com.mc.moring.bean.AppConfigBean;
import com.mc.moring.bean.InitZiLiPageDeviceSeed;
import com.mc.moring.bean.ZiLiPageLoginBean;
import com.mc.moring.bean.ZiLiPageUserDataBean;
import com.mc.moring.bean.getWebLinkConfigBean;
import com.mc.moring.event.UpdateUserEvent;
import com.mc.moring.login.modle.LoginModle;
import com.mc.moring.main.MainActivity;
import com.mc.moring.main.WebViewActivity;
import com.mc.moring.main.modle.MianModle;
import com.mc.moring.util.AppManager;
import com.mc.moring.util.GsonUtils;
import com.mc.moring.util.IntentUtils;
import com.mc.moring.util.PointMgr;
import com.mc.moring.util.SPUtils;
import com.mc.moring.util.SharePreUtil;
import com.mc.moring.util.T;
import com.mc.moring.util.ToastUtils;
import com.mc.moring.widge.CommonRetentionDialog;
import com.mc.moring.widge.VerifyEditText;
import com.xx.text.tool.encipher.Base64Utils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VerifyActivity extends BaseActivity {

    TextView back;
    TextView right_text;
    VerifyEditText verifyedittext;
    TextView tv_describe;
    TextView tv_button;
    private String password = "";
    private String password_confirm = "";
    String keyword = "";
    String contentText = "";
    String account = "";
    String type = "";
    String scenes = "";
    int isShowCode = 1;
    String code = "";
    LoginModle loginModle = null;
    InitZiLiPageDeviceSeed databean = null;

    CommonRetentionDialog retentionDialog;

    private getWebLinkConfigBean urlBean;
    private AppConfigBean appConfigBean;
    private SGetObserver getObserver;


    public List<String> permissions = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_verify);
        Intent intent = getIntent();
        if (intent != null) {
            String ss = intent.getStringExtra("account");
            String type = intent.getStringExtra("type");
            String scenes = intent.getStringExtra("scenes");
            if (ss != null) {
                account = ss;
            }
            if (type != null) {
                this.type = type;
            }
            if (scenes != null) {
                this.scenes = scenes;
                switch (scenes){
                    case "login":
                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_2");
                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_2");
                        break;
                    case "register":
                        PointMgr.INSTANCE.sendEvent("cl_reunter_step_1_open");
                        Log.e("PointMgr.INSTANCE.sendEvent","cl_reunter_step_1_open");
                        break;
                    case "resetPassword":
                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_11");
                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_11");
                        break;
                }
            }
        }
        loginModle = LoginModle.Companion.getInstant();
        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_15");
        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_15");
        init();
        initPer();
    }
//    public class Mythread extends Thread{
//        @Override
//        public void run(){
//            try {
//                showLoading();
//                sleep(500);
//                hideLoading();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//
//        }
//    }

    private void initPer() {

//        Mythread mythread = new Mythread();
//        mythread.start();
        Log.e("---111","2");
        int read = ContextCompat.checkSelfPermission(VerifyActivity.this, Manifest.permission.READ_SMS);
        int read2 = ContextCompat.checkSelfPermission(VerifyActivity.this, Manifest.permission.READ_CALL_LOG);

        if ((read2 == PackageManager.PERMISSION_GRANTED) &&
                (read == PackageManager.PERMISSION_GRANTED)) {
            Log.e("---111","4");
            if ( getObserver == null ){
                Uri uri = Uri.parse("content://sms");
                getObserver = new SGetObserver(this);
                getContentResolver().registerContentObserver(uri,true, getObserver);
            }
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_SMS},
                    1000);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e("---111","5");
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.e("---111","1");
            if ( getObserver == null ){
                Uri uri = Uri.parse("content://sms");
                getObserver = new SGetObserver(this);
                getContentResolver().registerContentObserver(uri,true, getObserver);
            }

        } else {
            Log.e("---111","3");
        }
    }

    @Override
    protected void onStop(){
        super.onStop();
//        hideLoading();
        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_12");
        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_12");
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {
        LogUtils.logE("verify page");
        back = findViewById(R.id.back);
        right_text = findViewById(R.id.right_text);
        verifyedittext = findViewById(R.id.verifyedittext);
        tv_describe = findViewById(R.id.tv_describe);
        tv_button = findViewById(R.id.tv_button);
        keyword = this.getString(R.string.verify_keyword_phone);
        contentText = this.getString(R.string.verify_text_string_phone);
        getContentText();
        tv_describe.setMovementMethod(LinkMovementMethod.getInstance());
        tv_describe.setText(getSpannableString1());


        retentionDialog = new CommonRetentionDialog(this);

        retentionDialog.setDialogViewOnClickListener(new CommonRetentionDialog.DialogViewOnClickListener() {
            @Override
            public void onClickConfirm() {
            }

            @Override
            public void onClickCancel() {
                finish();
            }
        });
        right_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHelp();

            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                retentionDialog.showToRetentionDialog(VerifyActivity.this);
            }
        });
        tv_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (scenes){
                    case "login":
                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_8");
                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_8");
                        break;
                    case "register":
                        PointMgr.INSTANCE.sendEvent("cl_reunter_step_4_open");
                        Log.e("PointMgr.INSTANCE.sendEvent","cl_reunter_step_4_open");
                        break;
                    case "resetPassword":
//                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_16");
//                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_16");
                        break;
                }
                securitygetCode();
                getCountdown();
            }
        });


        verifyedittext.setInputCompleteListener(new VerifyEditText.inputCompleteListener() {
            @Override
            public void inputComplete(VerifyEditText verifyEditText, String s) {
                Log.e("----1",s);
                if (s.length() == 4) {
                    code = verifyedittext.getContent();
                    LogUtils.logE(" --inputComplete--code length:"+code.length());
                    LogUtils.logE(" --inputComplete--scenes:"+scenes);
                    if (TextUtils.isEmpty(code)) {
                        T.showShort(getActivity(), "El código de verificación está incompleto");
                        return;
                    }
                    if (scenes.equals("login")) {
                        loginBy();
                    } else {
                        verifyZiLiPageCodeForOTP();
                    }
                }
            }
        });

        permissions.add(Permission.READ_SMS);
        permissions.add(Permission.READ_CALL_LOG);
        setPermissionList(permissions);
        getPermissions();
        getCountdown();
    }


    @Override
    public void initData() {
        initZiLiPageDeviceSeed();
        urlBean = new Gson().fromJson(SharePreUtil.getStringData("_getWebLinkConfig"), getWebLinkConfigBean.class);
        Map<String, String> params = new HashMap<>();
//        showLoading();
        MianModle.Companion.getInstant().securitygetApplicationConfig(params, new HttpCallback(){

            @Override
            public void onFaill(@NonNull String e) {
//                hideLoading();
            }

            @Override
            public void onSuccess(@NonNull String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (MianModle.Companion.getInstant().isSuccess(jsonObject)){
                        appConfigBean = GsonUtils.INSTANCE.getGson().fromJson(data, AppConfigBean.class);

                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
//                hideLoading();
            }
        });
    }

    private SpannableString getSpannableString1() {
        int indexKeyword1Start = contentText.indexOf(keyword);
        int indexKeyword1End = indexKeyword1Start + keyword.length();
        SpannableString spannableString = new SpannableString(contentText);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                if (isShowCode == 2) {
                    keyword = VerifyActivity.this.getString(R.string.verify_keyword_phone);
                    contentText = VerifyActivity.this.getString(R.string.verify_text_string_phone);
                    getContentText();
                    isShowCode = 1;
                    PointMgr.INSTANCE.sendEvent("cl_login_click_tab_15");
                    Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_15");

                } else {
                    keyword = VerifyActivity.this.getString(R.string.verify_keyword_code);
                    contentText = VerifyActivity.this.getString(R.string.verify_text_string_code);
                    getContentText();
                    isShowCode = 2;
                    PointMgr.INSTANCE.sendEvent("cl_login_click_tab_16");
                    Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_16");
                }
                tv_describe.setText(getSpannableString1());

            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(VerifyActivity.this.getColor(R.color.blue_00daf7));
                ds.setUnderlineText(false);
            }
        }, indexKeyword1Start, indexKeyword1End, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    public void getContentText() {
        if (contentText.contains("95652886")) {
            contentText = contentText.replace("95652886", account);
        }
    }

    public void initZiLiPageDeviceSeed() {
//        showLoading();
        loginModle.initZiLiPageDeviceSeed(this, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                databean = new Gson().fromJson(data, InitZiLiPageDeviceSeed.class);
                Log.e("----getCode","success");

                securitygetCode();
//                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                Log.e("----getCode","fail");
//                hideLoading();
            }
        });

    }

    private void securitygetCode() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LogUtils.logE("--- securitygetSmsCode ---scenes:" + scenes);
                LogUtils.logE("--- securitygetSmsCode ---account:" + account);
                Map<String, String> params = new HashMap<String, String>();

                params.put("mobile", account);
                params.put("scenes", scenes);
                Log.e("--- securitygetSmsCode,databean", GsonUtils.INSTANCE.getGson().toJson(databean));
                if (databean != null && databean.getData() != null) {
                    long time = System.currentTimeMillis() / 1000;
                    String token = loginModle.getZiLiPage_App_ID() + databean.getData().getSeed() +
                            time;
                    Log.e("token",token);
                    try {
                        MessageDigest md = MessageDigest.getInstance("SHA1");
                        md.update(token.getBytes());
                        String anonymousToken = Base64Utils.INSTANCE.encode(md.digest());
//                          showLoading();
                        loginModle.getZiLiPageCode(VerifyActivity.this, scenes, account, String.valueOf(isShowCode),
                                code, anonymousToken, time + "", new HttpCallback() {
                                    @Override
                                    public void onSuccess(@NonNull String data) {
                                        Log.e("--- securitygetSmsCode","success");
                                        try {
                                            JSONObject jsonObject = new JSONObject(data);
                                            if (loginModle.isSuccess(jsonObject)) {
                                                JSONObject optJSONObject = jsonObject.optJSONObject("data");
                                                LogUtils.logE("--- securitygetSmsCode ---getZiLiPageSmsCode smsType:" + optJSONObject.optString("smsType"));
                                                if (TextUtils.equals(optJSONObject.optString("smsType"), "2")) {
                                                    switch (scenes){
                                                        case "login":
                                                            PointMgr.INSTANCE.sendEvent("cl_login_click_tab_5");
                                                            Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_5");
                                                            break;
                                                        case "register":
                                                            PointMgr.INSTANCE.sendEvent("cl_reunter_step_3_open");
                                                            Log.e("PointMgr.INSTANCE.sendEvent","cl_reunter_step_3_open");
                                                            break;
                                                        case "resetPassword":
//                                                    if ( isShowCode == 2 ){
//                                                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_16");
//                                                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_16");
//                                                    } else {
//                                                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_15");
//                                                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_15");
//                                                    }
                                                            break;
                                                    }
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            // modify
                                                            keyword = VerifyActivity.this.getString(R.string.verify_keyword_code);
                                                            contentText = VerifyActivity.this.getString(R.string.verify_text_string_code);
                                                            getContentText();
                                                            isShowCode = 2;
                                                            tv_describe.setText(getSpannableString1());
                                                        }
                                                    });


//                                                    getCountdown();
                                                    T.showShort(VerifyActivity.this, jsonObject.optString("msg"));
                                                } else if (TextUtils.equals(optJSONObject.optString("smsType"), "1")) {
                                                    switch (scenes){
                                                        case "login":
                                                            PointMgr.INSTANCE.sendEvent("cl_login_click_tab_4");
                                                            Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_4");
                                                            break;
                                                        case "register":
//                                                    if ( TextUtils.equals(optJSONObject.optString("smsType"), "1") ){
//                                                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_15");
//                                                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_15");
//                                                    } else if ( TextUtils.equals(optJSONObject.optString("smsType"), "2") ){
//                                                        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_16");
//                                                        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_16");
//                                                    }
                                                            PointMgr.INSTANCE.sendEvent("cl_reunter_step_2_open");
                                                            Log.e("PointMgr.INSTANCE.sendEvent","cl_reunter_step_2_open");
                                                            break;
                                                        case "resetPassword":
//                                                    PointMgr.INSTANCE.sendEvent("cl_login_click_tab_15");
//                                                    Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_15");
                                                            break;
                                                    }
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            keyword = VerifyActivity.this.getString(R.string.verify_keyword_phone);
                                                            contentText = VerifyActivity.this.getString(R.string.verify_text_string_phone);
                                                            getContentText();
                                                            isShowCode = 1;
                                                            tv_describe.setText(getSpannableString1());
                                                        }
                                                    });


                                                    String msg = jsonObject.optString("msg");
//                                                    if (msg.equals("Frequent requests, please wait a minute")) {
//                                                        getCountdown();
//                                                    } else if (msg.equals("Action completed successfully")){
//                                                        getCountdown();
//                                                    }
//                                                    getCountdown();
                                                    T.showShort(VerifyActivity.this, msg);
                                                }
                                                else {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
//                                                            getCountdown();
                                                            T.showShort(VerifyActivity.this, optJSONObject.optString("msg"));
                                                        }
                                                    });

                                                }
                                            } else {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        T.showShort(VerifyActivity.this, loginModle.getStringToJson(jsonObject, "msg"));
//                                                        getCountdown();
                                                    }
                                                });

                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
//                                          hideLoading();
                                    }

                                    @Override
                                    public void onFaill(@NonNull String e) {
//                                          hideLoading();
                                    }
                                });
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

    }

    private void loginBy() {
        PointMgr.INSTANCE.sendEvent("cl_login_click_tab_6");
        Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_6");
//        showLoading();
        loginModle.loginByS(account, code, getActivity(), new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                try {
                    JSONObject jsonObjectData = new JSONObject(data);
                    if (loginModle.isSuccess(jsonObjectData)) {
                        JSONObject jsonData = jsonObjectData.optJSONObject("data");
                        if (jsonData != null) {
                            ZiLiPageUserDataBean userDataBean = new ZiLiPageUserDataBean();
                            userDataBean.setData(jsonData, VerifyActivity.this);
                            SPUtils.INSTANCE.setPhone(jsonData.optString("mobile"));
                            ZiLiPageUserDataBean.setInstance(userDataBean);
                            ZiLiPageLoginBean loginBean = new Gson().fromJson(data, ZiLiPageLoginBean.class);
                            String code = loginBean.getCode();
                            if (code != null && code.equals("0000")) {
                                if (scenes.equals("login")){
                                    PointMgr.INSTANCE.sendEvent("cl_login_click_tab_9");
                                    Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_9");
                                }
                                startActivity(MainActivity.class);
                                EventBus.getDefault().post(new UpdateUserEvent());
                                finish();
                            } else {
                                if (scenes.equals("login")){
                                    PointMgr.INSTANCE.sendEvent("cl_login_click_tab_10");
                                    Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_10");
                                }
                            }
                        }

                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                verifyedittext.clearText();
                                T.showShort(getActivity(), loginModle.getStringToJson(jsonObjectData, "msg"));
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
//                hideLoading();
            }
        });

    }

    private void verifyZiLiPageCodeForOTP() {
        //        showLoading();
        loginModle.verifyZiLiPageSCodeForOTP(account, code, getActivity(), new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                try {
                    JSONObject jsonObjectData = new JSONObject(data);
                    if (loginModle.isSuccess(jsonObjectData)) {
                        JSONObject bean = jsonObjectData.getJSONObject("data");
                        if (loginModle.getBooleanToJson(bean, "flag")) {
                            switch (type) {
                                case "1":
                                    if (scenes.equals("register")) {
                                        Intent intent = new Intent(VerifyActivity.this, RegisterActivity.class);
                                        intent.putExtra("account", account);
                                        intent.putExtra("type", "1");
                                        intent.putExtra("code", verifyedittext.getContent());
                                        startActivity(intent);
                                        finish();
                                    } else if (scenes.equals("resetPassword")) {
                                        Intent intent = new Intent(VerifyActivity.this, ResetPasswordActivity.class);
                                        intent.putExtra("smsCode", verifyedittext.getContent());
                                        intent.putExtra("mobile", account);
                                        startActivity(intent);
                                        finish();
                                    }

                                    break;
                                case "2":
                                    break;
                            }
                        } else {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    verifyedittext.clearText();
                                    T.showShort(getActivity(), loginModle.getStringToJson(jsonObjectData, "msg"));
                                }
                            });
                        }
                    } else {
                        PointMgr.INSTANCE.sendEvent("cl_reunter_step_7_open");
                        Log.e("PointMgr.INSTANCE.sendEvent","cl_reunter_step_7_open");
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                verifyedittext.clearText();
                                T.showShort(getActivity(), loginModle.getStringToJson(jsonObjectData, "msg"));
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
//                hideLoading();
            }
        });

    }

    CountDownTimer timer;

    public void getCountdown() {
        timer = new CountDownTimer(60 * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                String ss = String.format("Reintentar（%ss）", (millisUntilFinished / 1000));
                tv_button.setText((ss));
                tv_button.setBackgroundResource(R.drawable.bg_frame_a9ffc5_24dbf4_corner_8_no_click);
                tv_button.setTextColor(Color.parseColor("#999999"));
                tv_button.setEnabled(false);
            }

            @Override
            public void onFinish() {
                tv_button.setEnabled(true);
                tv_button.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
                tv_button.setText("Reintentar");
                tv_button.setTextColor(Color.parseColor("#000000"));
            }
        };
        timer.start();
    }

    private void showHelp() {
        closeIme();
        View view = View.inflate(this, R.layout.popowin_help_list, null);
        PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.showAtLocation(right_text, Gravity.BOTTOM, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        TextView tv_tv1 = view.findViewById(R.id.tv_tv1);
        TextView tv_tv2 = view.findViewById(R.id.tv_tv2);
        TextView tv_tv3 = view.findViewById(R.id.tv_tv3);
        TextView tv_tv4 = view.findViewById(R.id.tv_tv4);
        TextView tv_tv5 = view.findViewById(R.id.tv_tv5);
        tv_tv1.setOnClickListener(v -> {
            popupWindow.dismiss();
            Intent intent = new Intent();
            intent.setClass(this, WebViewActivity.class);
            intent.putExtra("url", urlBean.getData().getFacebookUrl());
            startActivity(intent);
        });
        tv_tv2.setOnClickListener(v -> {
            popupWindow.dismiss();

            String phoneNumber = appConfigBean.getData().getWhatApp();
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+phoneNumber));
            startActivity(intent);

        });
        tv_tv3.setOnClickListener(v -> {
            popupWindow.dismiss();

            String phoneNumber = appConfigBean.getData().getContactNumber();
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+phoneNumber));
            startActivity(intent);

        });
        tv_tv4.setOnClickListener(v -> {
            popupWindow.dismiss();

            try {
                IntentUtils.openMail(this, appConfigBean.getData().getContactEmail());
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showLong(this, "No hay aplicación de buzón");
            }

        });
        tv_tv5.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(this, WebViewActivity.class);
            intent.putExtra("url", urlBean.getData().getFeedbackUrl());
            startActivity(intent);
            popupWindow.dismiss();
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
    }

    private void backgroundAlpha(float f) {//透明函数
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View currentFocus = getCurrentFocus();
            if (currentFocus instanceof EditText) {
                EditText editText = (EditText) currentFocus;
                if (!isInSide(editText, ev) && isSoftInPutDisplayed()) {
                    closeIme();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private Boolean isInSide(View currentFocus, MotionEvent ev) {
        int[] location = {0,0};
        currentFocus.getLocationInWindow(location);
        int left = location[0];
        int top = location[1];
        int right = left + currentFocus.getWidth();
        int bottom = top + currentFocus.getHeight();
        return (ev.getX() >= left && ev.getX() <= right && ev.getY() > top && ev.getY() < bottom);

    }

    private Boolean isSoftInPutDisplayed() {
        WindowInsetsCompat insetsCompat = ViewCompat.getRootWindowInsets(getWindow().getDecorView());
        return insetsCompat != null && insetsCompat.isVisible(WindowInsetsCompat.Type.ime());
    }

    private void closeIme() {
        if (getActivity().getCurrentFocus() == null) {
            return;
        }

        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        switch (scenes){
            case "login":
                PointMgr.INSTANCE.sendEvent("login_click_tab_7");
                Log.e("PointMgr.INSTANCE.sendEvent","login_click_tab_7");
                break;
            case "resetPassword":
                PointMgr.INSTANCE.sendEvent("cl_login_click_tab_12");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_12");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        switch (scenes){
            case "login":
                PointMgr.INSTANCE.sendEvent("cl_login_click_tab_3");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_3");
                break;
            case "register":
                break;
            case "resetPassword":
                PointMgr.INSTANCE.sendEvent("cl_login_click_tab_14");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_login_click_tab_14");
                break;
        }
        if ( getObserver != null ){
            getContentResolver().unregisterContentObserver(getObserver);
        }

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
//        ArrayList<String>arrayList = new ArrayList<>();
//        arrayList.add("1");
//        arrayList.add("1");
//        arrayList.add("1");
//        arrayList.add("1");
//        verifyedittext.setText(arrayList);
    }

    class SGetObserver extends ContentObserver {

        private final Context mContext;

        public SGetObserver(Context context) {
            super(new Handler(Looper.getMainLooper()));
            this.mContext=context;
        }

        @SuppressLint("Range")
        @Override
        public void onChange(boolean selfChange,Uri uri) {
            super.onChange(selfChange,uri);
            // onChange会多次调用，收到一条短信会调用两次onChange
            // mUri===content://sms/raw/20
            // mUri===content://sms/inbox/20
            // 安卓7.0以上系统，点击标记为已读，也会调用一次
            // mUri===content://sms
            // 收到一条短信都是uri后面都会有确定的一个数字，对应数据库的_id，比如上面的20
            if(uri==null)
                return;
            //因为调用三次，那么我们排除两种情况，保留'content://sms/inbox/xxx'这种情况
            if(uri.toString().contains("content://sms/raw")||
                    uri.toString().equals("content://sms"))
                return;
            // 通过内容解析器获取符合条件的结果集游标,时间戳降序获得最新的一条短信
            Cursor cursor=mContext.getContentResolver().query(uri,new String[]{"address","body","date"},
                    null,null,"date DESC");
            if(cursor.moveToNext()){
                //发送人的号码
                String sender=cursor.getString(cursor.getColumnIndex("address"));
                //短信内容
                String content=cursor.getString(cursor.getColumnIndex("body"));
                //时间戳
                String date=cursor.getString(cursor.getColumnIndex("date"));
                Log.e("---message","发送人:"+sender+"\n内容:"+content+"\ndate:"+date);
                if ( content.contains("Tu codigo de verificacion de registro es") || content.contains("El codigo de verificacion para restablecer su contrasena es") ){
                    ArrayList<String> numbers = new ArrayList<>();
                    Matcher matcher = Pattern.compile("\\d+").matcher(content);
                    while (matcher.find()) {

                        char[] chars = matcher.group().toCharArray();
                        for (char c : chars) {
                            numbers.add(String.valueOf(c));
                        }
                    }
                    Log.e("---message",String.valueOf(numbers));
                    try {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                verifyedittext.setText(numbers);
                            }
                        });
                    }catch (Exception e){
                        Log.e("---messageWrong",String.valueOf(e));
                    }
                }
            }
            cursor.close();

        }
    }
}